﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using Matrix_network.Code;

/// <summary>
/// Сводное описание для MatrixData
/// </summary>
public class MatrixData
{
	private string _connectionString;
    private MatrixDataClassesDataContext context;
    private int val_length=16;
	public MatrixData()
	{
        Initialize();
	}

    /// <summary>
    /// Initialize data.
    /// </summary>
    public void Initialize()
    {
        if (ConfigurationManager.ConnectionStrings["TheMatrixNetConnectionString"] == null ||
      ConfigurationManager.ConnectionStrings["TheMatrixNetConnectionString"].ConnectionString.Trim() == "")
        {
            throw new Exception("A connection string named 'TheMatrixNetConnectionString' with a valid connection string " +
                        "must exist in the <connectionStrings> configuration section for the application.");
        }

        _connectionString =
        ConfigurationManager.ConnectionStrings["TheMatrixNetConnectionString"].ConnectionString;
        context =
            new MatrixDataClassesDataContext(_connectionString);
    }

    /// <summary>
    /// Get user id from login and password.
    /// </summary>
    /// <param name="login"></param>
    /// <param name="pass"></param>
    /// <returns></returns>
    public int getUserIdFromLoginAndPassword(string login,string pass)
    {
        string val="";
        string nonexistence="";
        int user_id = -1;
        for(int i=0;i<=val_length+1;i++)
            nonexistence+="A";
        val=nonexistence+"";
        ISingleResult<get_salt_from_loginResult> val_res 
            = context.get_salt_from_login(login);
        foreach (get_salt_from_loginResult res in val_res)
        {
            val = res.salt;            
        }
        if (!val.Equals(nonexistence))
        {
            ISingleResult<get_user_id_from_login_and_passwordResult> user_id_res
            = context.get_user_id_from_login_and_password(login,
            HashPassword(pass, val));

            foreach (get_user_id_from_login_and_passwordResult res in user_id_res)
            {
                user_id = res.id;
            }
        }
        return user_id;
    }

    /// <summary>
    /// Get user id from login.
    /// </summary>
    /// <param name="login"></param>
    /// <returns></returns>
    public int getUserIdFromLogin(string login)
    {

        ISingleResult<get_user_id_from_loginResult> user_id_res = context.get_user_id_from_login(login);
        int user_id = -1;

        foreach (get_user_id_from_loginResult res in user_id_res)
        {
            user_id = res.id;
        }
        return user_id;

    }

    /// <summary>
    /// Add user record to database.
    /// </summary>
    /// <param name="name"></param>
    /// <param name="surname"></param>
    /// <param name="foto"></param>
    /// <param name="birthday"></param>
    /// <param name="city"></param>
    /// <param name="about"></param>
    /// <param name="login"></param>
    /// <param name="pass"></param>
    public void addUser(string name, string surname, 
        DateTime birthday,string city, string login,
        string pass)
    {
        string val = generateVal();
        context.add_user(name, surname, birthday, city, login, HashPassword(pass,val),val);
    }


    public void addUserWithFoto(string name, string surname,
        DateTime birthday, string city, string login,
        string pass, byte[]foto)
    {
        string val = generateVal();
        context.add_user_with_photo(name, surname, birthday, city, login, HashPassword(pass, val), val,foto);
    }

    /// <summary>
    /// add friend to current user
    /// </summary>
    /// <param name="id">current user's id</param>
    /// <param name="friendId">friend's id</param>
    public void addFriend(int id, int friendId)
    {
       context.add_friend(id, friendId);
    }

    public static byte[] HashPassword(string pass,string val)
    {
        Encoding utf8 = Encoding.UTF8;
        byte[] hash;
        byte[] data = utf8.GetBytes(pass+val);
        hash = new SHA256Managed().ComputeHash(data);
        return hash;
    }

    private string generateVal()
    {
        int length = 16;
        string val = "";
        Random rand=new Random();
        for (int i = 0; i < length; i++)
        {
             
            val=val+(char)((int)(rand.NextDouble()*65535));    
        }
        return val;
    }

    public int getAvaId(int id)
    {
        ISingleResult<get_ava_idResult> ava
                    = context.get_ava_id(id);
        foreach (get_ava_idResult r in ava)
        {
            if (r.ava_id != null)
                return (int)r.ava_id;
        }
        return -1;
    }

    
}